<template>
  <div class="app-container">
    <!-- 顶部：左侧新建，右侧搜索表单 -->
    <el-card shadow="never" class="header-card">
      <div class="table-header">
        <div class="header-left">
          <el-button type="primary" @click="handleAdd">新建</el-button>
        </div>
        <div class="header-right">
          <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="queryParams.orderNo" placeholder="请输入采购单号" clearable style="width: 200px" />
        </el-form-item>
            <el-form-item label="采购类型">
          <el-select v-model="queryParams.purchaseType" placeholder="请选择采购类型" clearable style="width: 150px">
                <el-option v-for="dict in purchaseTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
            <el-form-item label="采购状态">
          <el-select v-model="queryParams.storageStatus" placeholder="请选择入库状态" clearable style="width: 150px">
                <el-option v-for="dict in storageStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
            <el-form-item label="付款状态">
          <el-select v-model="queryParams.paymentStatus" placeholder="请选择付款状态" clearable style="width: 150px">
                <el-option v-for="dict in paymentStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
            <el-form-item label="期望入库时间">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 220px" />
        </el-form-item>
      </el-form>
          <!-- 第三行：搜索/重置按钮 -->
          <div class="actions-row">
            <el-button type="primary" :loading="loading" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 表格数据 -->
    <el-table ref="orderTable" v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购订单号" align="center" prop="orderNo" width="180">
        <template #default="{ row }">
          <el-link type="primary">{{ row.orderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="采购类型" align="center" prop="purchaseType" width="100">
        <template #default="{ row }">
          <span>{{ purchaseTypeText(row.purchaseType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="期望入库时间" align="center" prop="expectedStorageTime" width="120">
        <template #default="{ row }">
          <span>{{ parseTime(row.expectedStorageTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="uId" width="100">
        <template #default="{ row }">
          <span>{{ row.purchaserName || row.purcharseName || row.buyerName || row.userName || userIdToName[row.uId] || userIdToName[String(row.uId)] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplierName" width="120" />
      <el-table-column label="采购数量" align="center" prop="purchaseQuantity" width="100" />
      <el-table-column label="采购金额" align="center" prop="purchaseAmount" width="120">
        <template #default="{ row }">
          <span>¥{{ row.purchaseAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库状态" align="center" prop="storageStatus" width="100">
        <template #default="{ row }">
          <el-tag :type="row.storageStatus === '2' ? 'success' : row.storageStatus === '1' ? 'warning' : 'info'">
            {{ storageStatusFormat(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采购入库单" align="center" prop="storageOrderNo" width="180">
        <template #default="{ row }">
          <el-link v-if="row.storageOrderNo || (row.storageOrderNoList && row.storageOrderNoList.length) || row.storageOrderNoStr" type="primary">
            {{ row.storageOrderNo || (Array.isArray(row.storageOrderNoList) ? row.storageOrderNoList.join(',') : '') || row.storageOrderNoStr }}
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="已采购入库数量" align="center" prop="storedQuantity" width="140">
        <template #default="{ row }">{{ row.storedQuantity ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="待采购数量" align="center" width="120">
        <template #default="{ row }">{{ calcToPurchase(row) }}</template>
      </el-table-column>
      <el-table-column label="已退货数量" align="center" prop="returnedQuantity" width="120">
        <template #default="{ row }">{{ row.returnedQuantity ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="paymentStatus" width="100">
        <template #default="{ row }">
          <el-tag :type="row.paymentStatus === '2' ? 'success' : row.paymentStatus === '1' ? 'warning' : 'info'">
            {{ paymentStatusFormat(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="已付款金额" align="center" prop="paidAmount" width="120">
        <template #default="{ row }">¥{{ formatAmount(row.paidAmount) }}</template>
      </el-table-column>
      <el-table-column label="待付款金额" align="center" width="120">
        <template #default="{ row }">¥{{ formatAmount(calcUnpaid(row)) }}</template>
      </el-table-column>
    </el-table>

    <!-- 底部：左侧全选+导出，右侧分页 + 条数下拉） -->
    <div class="footer-bar">
      <div class="footer-left">
        <el-checkbox v-model="selectAll" @change="toggleSelectAll">全选</el-checkbox>
        <el-button size="small" style="margin-left: 12px" @click="handleExport">导出</el-button>
      </div>
      <div class="footer-center"></div>
      <div class="footer-right">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
        :total="total"
          :page-sizes="[5,10,20,50,100]"
          layout="prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入采购单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购类型" prop="purchaseType">
              <el-select v-model="form.purchaseType" placeholder="请选择采购类型" style="width: 100%">
                <el-option
                    v-for="dict in purchaseTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                  v-model="form.supplierId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入供应商名称或编码"
                  :remote-method="getSupplierList"
                  :loading="supplierLoading"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in supplierOptions"
                    :key="item.id"
                    :label="item.supplierName"
                    :value="item.id"
                >
                  <span style="float: left">{{ item.supplierName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.supplierCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期望入库时间" prop="expectedStorageTime">
              <el-date-picker
                  v-model="form.expectedStorageTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购数量" prop="purchaseQuantity">
              <el-input-number v-model="form.purchaseQuantity" :min="1" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购金额" prop="purchaseAmount">
              <el-input-number v-model="form.purchaseAmount" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchaseOrder, generateOrderNo, delPurchaseOrder, exportPurchaseOrder } from '@/api/purchase/purchase.js'
import { getUserListForDropdown } from '@/api/purchase/User.js'
export default {
  name: "PurchaseOrder",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 采购类型字典
      purchaseTypeOptions: [],
      // 入库状态字典
      storageStatusOptions: [],
      // 付款状态字典
      paymentStatusOptions: [],
      // 供应商列表
      supplierOptions: [],
      // 供应商加载状态
      supplierLoading: false,
      // 用户映射
      userOptions: [],
      userIdToName: {},
      // 全选开关
      selectAll: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        purchaseType: undefined,
        storageStatus: undefined,
        paymentStatus: undefined,
        expectedStorageStartTime: undefined,
        expectedStorageEndTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "采购单号不能为空", trigger: "blur" }
        ],
        purchaseType: [
          { required: true, message: "采购类型不能为空", trigger: "change" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        purchaseQuantity: [
          { required: true, message: "采购数量不能为空", trigger: "blur" },
          { type: 'number', min: 1, message: '采购数量必须大于0' }
        ],
        purchaseAmount: [
          { required: true, message: "采购金额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: '采购金额不能小于0' }
        ],
        expectedStorageTime: [
          { required: true, message: "期望入库时间不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadUserMap();
    if (this.getDicts) {
      this.getDicts("purchase_type").then(response => { this.purchaseTypeOptions = response.data || [] });
      this.getDicts("storage_status").then(response => { this.storageStatusOptions = response.data || [] });
      this.getDicts("payment_status").then(response => { this.paymentStatusOptions = response.data || [] });
    } else {
      this.purchaseTypeOptions = [
        { dictValue: 0, dictLabel: '生产采购' },
        { dictValue: 1, dictLabel: '备货采购' }
      ]
      this.storageStatusOptions = [
        { dictValue: 0, dictLabel: '待入库' },
        { dictValue: 1, dictLabel: '部分入库' },
        { dictValue: 2, dictLabel: '全部入库' }
      ]
      this.paymentStatusOptions = [
        { dictValue: 0, dictLabel: '待付款' },
        { dictValue: 1, dictLabel: '部分付款' },
        { dictValue: 2, dictLabel: '已付款' },
        { dictValue: 3, dictLabel: '已退货' }
      ]
    }
  },
  methods: {
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.queryParams.pageNum = 1
      this.getList()
    },
    handlePageChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    toggleSelectAll(val) {
      // 设置表格勾选状态
      const table = this.$refs.orderTable
      if (!table) return
      if (val) {
        table.toggleAllSelection && table.toggleAllSelection()
      } else {
        table.clearSelection && table.clearSelection()
      }
    },
    calcToPurchase(row) {
      const qty = Number(row.purchaseQuantity || 0)
      const stored = Number(row.storedQuantity || 0)
      return Math.max(qty - stored, 0)
    },
    calcUnpaid(row) {
      const amount = Number(row.purchaseAmount || 0)
      const paid = Number(row.paidAmount || 0)
      return Math.max(amount - paid, 0)
    },
    async loadUserMap() {
      try {
        const res = await getUserListForDropdown();
        const payload = res?.data || res
        const ok = payload?.code === 200 || payload?.success === true
        const list = ok ? (payload.data || []) : []
        this.userOptions = list
        const map = {}
        list.forEach(item => { map[item.value] = item.label })
        this.userIdToName = map
      } catch (e) {
        this.userIdToName = {}
      }
    },
    purchaseTypeText(val) {
      const found = (this.purchaseTypeOptions || []).find(i => Number(i.dictValue) === Number(val))
      return found ? found.dictLabel : ''
    },
    storageStatusText(val) {
      const found = (this.storageStatusOptions || []).find(i => Number(i.dictValue) === Number(val))
      return found ? found.dictLabel : ''
    },
    paymentStatusText(val) {
      const found = (this.paymentStatusOptions || []).find(i => Number(i.dictValue) === Number(val))
      return found ? found.dictLabel : ''
    },
    // 本地 parseTime，兼容字符串/时间戳/Date
    parseTime(val, fmt = '{y}-{m}-{d}') {
      if (!val) return ''
      let d
      if (typeof val === 'string') {
        if (/^\d{4}-\d{2}-\d{2}/.test(val)) {
          // 已经是 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss
          return fmt === '{y}-{m}-{d}' ? val.substring(0, 10) : val
        }
        const n = Number(val)
        d = isNaN(n) ? new Date(val) : new Date(n)
      } else if (typeof val === 'number') {
        d = new Date(val)
      } else if (val instanceof Date) {
        d = val
      } else {
        return ''
      }
      const y = d.getFullYear()
      const m = (`0${d.getMonth() + 1}`).slice(-2)
      const day = (`0${d.getDate()}`).slice(-2)
      const h = (`0${d.getHours()}`).slice(-2)
      const i = (`0${d.getMinutes()}`).slice(-2)
      const s = (`0${d.getSeconds()}`).slice(-2)
      return fmt
        .replace('{y}', y)
        .replace('{m}', m)
        .replace('{d}', day)
        .replace('{h}', h)
        .replace('{i}', i)
        .replace('{s}', s)
    },
    formatAmount(v) {
      if (v === null || v === undefined || v === '') return '0.00'
      const num = Number(v)
      if (Number.isNaN(num)) return '0.00'
      return num.toFixed(2)
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      // 发起请求前清空当前表格，避免用户感知为“第二页还是第一页内容”
      this.orderList = []
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.expectedStorageStartTime = this.dateRange[0]
        this.queryParams.expectedStorageEndTime = this.dateRange[1]
      } else {
        this.queryParams.expectedStorageStartTime = undefined
        this.queryParams.expectedStorageEndTime = undefined
      }

      // 调用新API并解析标准Result + Page结构
      this.$nextTick(() => {
        listPurchaseOrder(this.queryParams).then(res => {
          const payload = res?.data || res
          const ok = payload?.code === 200 || payload?.success === true
          const data = ok ? (payload.data ?? payload.result ?? payload.page ?? payload) : null
          // 兼容多种分页结构：{records,total} 或 {page:{records,total}} 等
          const page = data?.records ? data
            : data?.page?.records ? data.page
            : data?.data?.records ? data.data
            : data
          const records = page?.records || []
          let total = page?.total
          if (total === undefined || total === null) {
            total = page?.totalCount ?? page?.count
          }
          // 若后端 total=0 但返回了数据，做兜底修正
          if ((total === 0 || total === '0') && Array.isArray(records) && records.length > 0) {
            total = records.length
          }
          if (total === undefined || total === null) {
            total = Array.isArray(records) ? records.length : 0
          }
          this.orderList = records
          this.total = Number(total || 0)
          // 保持分页以用户选择为准，不被后端 size/current 覆盖
        }).finally(() => {
          this.loading = false
        })
      })
    },
    // 获取供应商列表（若已存在供应商接口，可替换调用）
    getSupplierList(query) {
      if (query !== '') {
        this.supplierLoading = true;
        listSupplier({ supplierName: query, pageSize: 10 }).then(response => {
          this.supplierOptions = response.rows;
          this.supplierLoading = false;
        });
      }
    },
    // 入库状态字典翻译
    storageStatusFormat(row) {
      return this.storageStatusText(row.storageStatus)
    },
    // 付款状态字典翻译
    paymentStatusFormat(row) {
      return this.paymentStatusText(row.paymentStatus)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        orderNo: undefined,
        purchaseType: undefined,
        supplierId: undefined,
        expectedStorageTime: undefined,
        purchaseQuantity: 1,
        purchaseAmount: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = { orderNo: '', purchaseType: '', pageNum: 1, pageSize: 10 }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
      // 生成采购单号
      // 从后端生成采购单号
      generateOrderNo().then(res => {
        const payload = res?.data || res
        this.form.orderNo = payload?.data || ''
      }).catch(() => {
        this.form.orderNo = 'PO' + new Date().getTime()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getPurchaseOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push(`/purchase/order/detail/${row.id}`);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchaseOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchaseOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row?.id ? [row.id] : this.ids
      if (!ids || ids.length === 0) return
      this.$modal.confirm('是否确认删除所选采购订单？').then(() => {
        return delPurchaseOrder(ids.join(','))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const qp = { ...this.queryParams }
      this.$modal.confirm('是否确认导出采购订单数据？').then(() => {
        this.exportLoading = true
        return exportPurchaseOrder(qp)
      }).then(() => {
        this.$modal.msgSuccess('已开始下载')
      }).finally(() => {
        this.exportLoading = false
      })
    }
  }
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.el-table .cell {
  white-space: nowrap;
}
.header-card { margin-bottom: 16px; }
.table-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; }
.header-left, .header-right { display: flex; align-items: center; }
.header-left { width: 100%; margin-bottom: 8px; }
.header-right { width: 100%; }
.actions-row { margin-top: 8px; display: flex; justify-content: flex-end; }
.footer-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; }
.footer-left, .footer-center, .footer-right { display: flex; align-items: center; }
</style>
